package com.zhangxin.aiInterview.manager.work_flow.ai_tec_interviewer.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONArray;
import com.zhangxin.aiInterview.manager.work_flow.ai_tec_interviewer.constants.CozeConstants;
import org.springframework.stereotype.Service;

import static com.zhangxin.aiInterview.manager.work_flow.ai_tec_interviewer.constants.CozeConstants.TOKEN;

/**
 * 发起对话
 */
@Service
public class StartChat {


    /**
     * 发起对话
     * @param conversationId 会话id
     * @param userContent 用户回答
     * @return 对话id
     */
    public String start(String conversationId,Long userId,String userContent) {
        String url = "https://api.coze.cn/v3/chat?conversation_id=" + conversationId;

        JSONObject body = new JSONObject();
        body.set("bot_id", CozeConstants.BOT_ID);
        body.set("user_id", userId.toString());
        body.set("stream", false);
        body.set("auto_save_history", true);

        JSONArray additionalMessages = new JSONArray();
        JSONObject message = new JSONObject();
        message.set("role", "user");
        message.set("content", userContent);
        message.set("content_type", "text");
        additionalMessages.add(message);
        body.set("additional_messages", additionalMessages);

        HttpResponse response = HttpRequest.post(url)
            .header("Authorization", TOKEN)
            .header("Content-Type", "application/json")
            .body(body.toString())
            .execute();

        JSONObject result = JSONUtil.parseObj(response.body());
        return result.getJSONObject("data").getStr("id");
    }
}
